package logic

import (
	"book-hub/cache"
	"book-hub/models"
	"context"
	"encoding/json"
	"strconv"
	"time"

	"book-hub/bookrpc/bookrpc"
	"book-hub/bookrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NovelCommentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNovelCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NovelCommentLogic {
	return &NovelCommentLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *NovelCommentLogic) NovelComment(in *bookrpc.NovelCommentRequest) (*bookrpc.NovelCommentResponse, error) {
	// todo: add your logic here and delete this line
	var novel []models.NovelComment
	result, _ := cache.Rdb.Get(cache.Ctx, "NovelComment"+strconv.Itoa(int(in.NovelId))).Result()
	if result == "" {
		models.DB.Debug().Model(&models.Novel{}).
			Select(" novels.*,  comments.content").
			Joins("LEFT JOIN comments ON comments.novel_id = novels.id").
			Where("novel_id=?", in.NovelId).
			Order("comments.created_at desc").
			Find(&novel)
		marshal, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, "NovelComment"+strconv.Itoa(int(in.NovelId)), marshal, time.Minute*15)
	} else {
		json.Unmarshal([]byte(result), novel)
	}
	var novelComments []*bookrpc.NovelComment
	for _, comment := range novel {
		novelComment := bookrpc.NovelComment{
			Title:          comment.Title,
			Class:          comment.Class,
			Label:          comment.Label,
			Introduction:   comment.Introduction,
			UserId:         int64(comment.UserId),
			CollectCount:   int64(comment.CollectCount),
			CommentContent: comment.Content,
		}
		novelComments = append(novelComments, &novelComment)
	}

	return &bookrpc.NovelCommentResponse{
		List: novelComments,
	}, nil
}
